package cc.rengu.redp.bizimpl.igas.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.enums.SettleAccTypeEnum;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelInfo;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 支付通道管理
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-08
 */
@Slf4j
@Api(tags = "产品管理:支付通道管理")
@RestController
@RequestMapping("/admin/igas/pDstChannelInfo")
public class PDstChannelInfoController extends BaseController {

    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;

    @GetMapping
//    @RequiresPermissions("areaInfo:view")
    public Map<String, Object> list(QueryRequest request, PDstChannelInfo entity) {
        return getDataTable(this.pDstChannelInfoService.findByPage(request, entity));
    }

    @Log("编辑查询")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作符", required = true, dataType = "String")
    })
    public Map<String, Object> getEdit(@NotBlank(message = "{required}") String dstChannelId, @NotBlank(message = "{required}") String instId,
                                       @NotBlank(message = "{required}") String optFlag) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        List<LabelValueBean> yesOrNo = Lists.newArrayList();
        yesOrNo.add(new LabelValueBean("是", IgasYesOrNoEnum.Yes.getType()));
        yesOrNo.add(new LabelValueBean("否", IgasYesOrNoEnum.No.getType()));
        result.put("yesOrNo", yesOrNo);
        List<LabelValueBean> accTypes = Lists.newArrayList();
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.ALL_ACCOUNT.getDesc(), SettleAccTypeEnum.ALL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_DEBIT_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_DEBIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_CREDIT_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_CREDIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_BANKBOOK.getDesc(), SettleAccTypeEnum.INNER_BANKBOOK.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_INTERNAL_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_INTERNAL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_PUBLIC_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_PUBLIC_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_DEBIT_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_DEBIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_CREDIT_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_CREDIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_BANKBOOK.getDesc(), SettleAccTypeEnum.OTHER_BANKBOOK.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_INTERNAL_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_INTERNAL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_PUBLIC_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_PUBLIC_ACCOUNT.getType()));
        result.put("accTypes", accTypes);
        PDstChannelInfo entity = new PDstChannelInfo();
       /* LambdaQueryWrapper<PDstChannelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PDstChannelInfo::getInstId, instId);
        wrapper.eq(PDstChannelInfo::getDstChannelId, dstChannelId);
        PDstChannelInfo entity = pDstChannelInfoService.getOne(wrapper);
      */

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            //暂时不支持新增操作
            //由于这几个字段是必填，这里预先赋值否则录入界面因为隐藏输入域而无法通过非空校验
            entity.setDstChannelStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            entity.setInstId(instId);
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            //审核查询显示临时表数据，转换成对应实体
            log.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        } else {
            entity = this.getOne(instId, dstChannelId);
            if (Common.isBlank(entity)) {
                log.error("根据唯一索引没有找到指定数据！");
                throw new RedpException("根据唯一索引没有找到指定数据！");
            }
            List<String> supportedAcctTypes = Lists.newArrayList();
            if ("*".equals(entity.getSupportAcctType())) {
                for ( LabelValueBean bean: accTypes) {
                    if (!bean.getValue().equals("*"))
                    supportedAcctTypes.add(bean.getValue());
                }
            } else if (Common.isNotBlank(entity.getSupportAcctType()) && entity.getSupportAcctType().length() >= 10) {

                String[] acctypes = entity.getSupportAcctType().split("");
                for (int i = 0; i < 10; i++) {
                    if (IgasYesOrNoEnum.Yes.getType().equals(acctypes[i])) {
                        supportedAcctTypes.add(accTypes.get(i + 1).getValue());
                    }
                }
            } else {
                log.info("entity.getSupportAcctType() 值长度为{}，不符合规范", null == entity.getSupportAcctType() ? 0 : entity.getSupportAcctType().length());
            }
            entity.setSupportAcctTypeList(supportedAcctTypes);
        }

        entity.setOptFlag(optFlag);
        entity.setBizTimeFlag(IgasYesOrNoEnum.No.getType());
        result.put("entity", entity);
        result.put("optFlag", optFlag);
        return result;
    }

    @GetMapping(value = "/edit-tabs")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作符", required = true, dataType = "String")
    })
    public Map<String, Object> editTabs(@NotBlank(message = "{required}") String optFlag) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();

        if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_VIEW.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
        ) {
            result.put("optFlag", optFlag);
            result.put("tabActive", 0);
        } else {
            log.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        }

        return result;
    }

    @Log("查询单条")
    @GetMapping(value = "/getOne")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public PDstChannelInfo getOne(@NotBlank(message = "{required}") String instId, @NotBlank(message = "{required}") String dstChannelId) {
        LambdaQueryWrapper<PDstChannelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PDstChannelInfo::getInstId, instId);
        wrapper.eq(PDstChannelInfo::getDstChannelId, dstChannelId);
        return pDstChannelInfoService.getOne(wrapper);
    }

    @GetMapping(value = "/editTime")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作符", required = true, dataType = "String")
    })
    public Map<String, Object> editTime(@NotBlank(message = "{required}") String optFlag, @NotBlank(message = "{required}") String dstChannelId, @NotBlank(message = "{required}") String instId) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();

        PDstChannelInfo entity = this.getOne(instId, dstChannelId);
        if (Common.isBlank(entity)) {
            log.error("根据唯一索引没有找到指定数据！");
            throw new RedpException("根据唯一索引没有找到指定数据！");
        }

        entity.setBizTimeFlag(IgasYesOrNoEnum.Yes.getType());
        entity.setOptFlag(optFlag);
        result.put("entity", entity);
        result.put("optFlag", optFlag);
        return result;
    }


    @Log("修改")
    @PutMapping("/update")
//    @RequiresPermissions("areaInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelName", value = "通道名称", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public void update(@Valid PDstChannelInfo entity) throws RedpException {
        try {
            String bizStartTime = entity.getBizStartTime();
            String bizEndTime = entity.getBizEndTime();
            if (!bizStartTime.equals("*") || !bizEndTime.equals("*")){
                try {
                    if (!bizStartTime.equals("*") && bizStartTime.length()!=6){
                        int i=0;
                        String substring = bizStartTime.substring(0, 2);
                        String substring1 = bizStartTime.substring(3, 4);
                        String substring2 = bizStartTime.substring(5, 6);
                        if (Integer.valueOf(substring)<=24){
                            i++;
                        }
                        if (Integer.valueOf(substring1)<=60){
                            i++;
                        }
                        if (Integer.valueOf(substring2)<=60){
                            i++;
                        }
                        if (i!=3){
                            log.info("营业开始时间不符合格式,请重新输入");
                            throw new RedpException("营业开始时间不符合格式,请重新输入");
                        }
                    }
                    if (!bizEndTime.equals("*") && bizEndTime.length()!=6){
                        int i=0;
                        String substring = bizEndTime.substring(0, 2);
                        String substring1 = bizEndTime.substring(3, 4);
                        String substring2 = bizEndTime.substring(5, 6);
                        if (Integer.valueOf(substring)<=24){
                            i++;
                        }
                        if (Integer.valueOf(substring1)<=60){
                            i++;
                        }
                        if (Integer.valueOf(substring2)<=60){
                            i++;
                        }
                        if (i!=3) {
                            log.info("营业截止时间不符合格式,请重新输入");
                            throw new RedpException("营业截止时间不符合格式,请重新输入");
                        }
                    }
                }catch (NumberFormatException e){
                    log.info("营业开始时间或营业截止时间不符合格式,请重新输入");
                    throw e;
                }
            }
            this.pDstChannelInfoService.update(entity);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }
    @Log("停用")
    @PutMapping("/changeStatus")
//    @RequiresPermissions("areaInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelName", value = "通道名称", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public void changeStatus(@Valid PDstChannelInfo entity) throws RedpException {
      try {
          if (entity.getDstChannelStatus().equals("Y")){
              entity.setDstChannelStatus("N");
          }else {
              entity.setDstChannelStatus("Y");
          }
          QueryWrapper queryWrapper=new QueryWrapper();
          queryWrapper.eq("inst_Id", entity.getInstId());
          queryWrapper.eq("dst_channel_id", entity.getDstChannelId());
        pDstChannelInfoService.update(entity, queryWrapper);
      } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }
}
